package cn.yuanqiao.cqbc.fileBackup.util;

import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

/**
 * @version 1.0
 * @author： xy
 * @date： 2023-03-01 09:44
 */
@Component
public class FileUtil {
    public  void copy(File originalFile, File backupFile, String originalAddress) throws IOException {
        if (!backupFile.exists()) {
            backupFile.mkdirs();
        }
        if (originalFile.isDirectory()) {
            File[] files = originalFile.listFiles();
            for (File file2 : files) {
                if (file2.isDirectory()) {
                    copy(file2, new File(backupFile.getPath(), file2.getName()),originalAddress);
                } else {


                    Files.copy(file2.toPath(), Paths.get(backupFile.getPath() +File.separator+file2.getName()), StandardCopyOption.REPLACE_EXISTING);
                }

            }

        }
    }
    public  void incrementCopy(File originalFile, File backupFile,String originalAddress) throws IOException {
        if (!backupFile.exists()) {
            backupFile.mkdirs();
        }
        if (originalFile.isDirectory()) {
            File[] files = originalFile.listFiles();
            for (File file2 : files) {
                if (file2.isDirectory()) {
                    incrementCopy(file2, new File(backupFile.getPath(), file2.getName()),originalAddress);
                } else {
                    //判断文件是否存在如果存在不在备份
                    File file=new File(backupFile.getPath() + file2.getPath().substring(originalAddress.length()));
                    if(!file.exists()||file2.length()!=file.length()) {
                        Files.copy(file2.toPath(),Paths.get(backupFile.getPath()+File.separator+file2.getName() ), StandardCopyOption.REPLACE_EXISTING);
                    }
                }

            }

        }
    }



}
